package com.catazy.cameralib.ui.cameraScreen

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import com.catazy.cameralib.ScanSurfaceListener
import com.catazy.cameralib.databinding.FragmentCameraScreenBinding
import com.catazy.cameralib.model.ScannerErrorModel
import com.catazy.cameralib.ui.InternalScanActivity
import com.catazy.cameralib.ui.base.BaseFragment
import com.catazy.cameralib.util.FileUriUtils
import java.io.File
import java.io.FileNotFoundException

/**
 * 作者: Tao
 * 日期: 2024/3/7
 * 时间: 16:16
 * 描述: 相机界面
 */
internal class CameraScreenFragment : BaseFragment(), ScanSurfaceListener {

    companion object {
        private val TAG = CameraScreenFragment::class.simpleName
        fun newInstance() = CameraScreenFragment()

    }

    private var resultLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == Activity.RESULT_OK) {
                try {
                    val imageUri = result?.data?.data
                    if (imageUri != null) {
                        val realPath = FileUriUtils.getRealPath(getScanActivity(), imageUri)
                        if (realPath != null) {
                            getScanActivity().reInitOriginalImageFile()
                            getScanActivity().originalImageFile = File(realPath)
//                            startCroppingProcess()
                        } else {
                            Log.e(
                                TAG,
                                ScannerErrorModel.ErrorMessage.TAKE_IMAGE_FROM_GALLERY_ERROR.error
                            )
                            onError(
                                ScannerErrorModel(
                                    ScannerErrorModel.ErrorMessage.TAKE_IMAGE_FROM_GALLERY_ERROR,
                                    null
                                )
                            )
                        }
                    } else {
                        Log.e(
                            TAG,
                            ScannerErrorModel.ErrorMessage.TAKE_IMAGE_FROM_GALLERY_ERROR.error
                        )
                        onError(
                            ScannerErrorModel(
                                ScannerErrorModel.ErrorMessage.TAKE_IMAGE_FROM_GALLERY_ERROR, null
                            )
                        )
                    }
                } catch (e: FileNotFoundException) {
                    Log.e(TAG, "FileNotFoundException", e)
                    onError(
                        ScannerErrorModel(
                            ScannerErrorModel.ErrorMessage.TAKE_IMAGE_FROM_GALLERY_ERROR, e
                        )
                    )
                }
            }
        }

    private var _binding: FragmentCameraScreenBinding? = null
    private val mBinding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentCameraScreenBinding.inflate(inflater, container, false)
        return mBinding.root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initSurfaceView()
        initClickListener()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (getScanActivity().shouldCallOnClose) {
            getScanActivity().onClose()
        }
    }

    override fun onResume() {
        super.onResume()
        getScanActivity().reInitOriginalImageFile()
        mBinding.scanSurfaceView.originalImageFile = getScanActivity().originalImageFile
    }

    private fun initSurfaceView() {
        mBinding.scanSurfaceView.apply {
            lifecycleOwner = this@CameraScreenFragment
            listener = this@CameraScreenFragment
            originalImageFile = getScanActivity().originalImageFile
            start()
        }
    }

    private fun initClickListener() {
        mBinding.cameraCaptureButton.setOnClickListener {
            mBinding.scanSurfaceView.takePicture()
        }
        mBinding.cancelButton.setOnClickListener {
            getScanActivity().finish()
        }
        mBinding.galleryButton.setOnClickListener {
            val photoPickerIntent = Intent(Intent.ACTION_OPEN_DOCUMENT)
            photoPickerIntent.addCategory(Intent.CATEGORY_OPENABLE)
            photoPickerIntent.type = "image/*"
            resultLauncher.launch(photoPickerIntent)
        }
    }

    private fun getScanActivity(): InternalScanActivity {
        return activity as InternalScanActivity
    }


    override fun scanSurfacePictureTaken(bitmap: Bitmap) {
    }

    override fun scanSurfaceShowProgress() {
    }

    override fun scanSurfaceHideProgress() {
    }

    override fun onError(error: ScannerErrorModel) {
    }

    override fun showFlash() {
    }

    override fun hideFlash() {
    }

    override fun showFlashModeOn() {
    }

    override fun showFlashModeOff() {
    }
}